<template>
  <div class="home-container">
    <!-- 顶部标题和登录状态栏 -->
    <header class="header">
      <h1 class="title">IoT 监控</h1>
      <div class="task-control">
        <el-switch
          v-model="taskEnabled"
          @change="toggleTask"
        />
        <span class="status-text">
          当前状态: {{ taskEnabled ? '运行中' : '已停止' }}
        </span>
      </div>
      <div class="auth-status">
        <span class="username">admin</span>
        <button class="logout-btn" @click="handleLogout">退出登录</button>
      </div>
    </header>

    <!-- 主内容区 - 左右分块 -->
    <main class="main-content">
      <!-- 左侧区块 (60%) -->
      <section class="left-section">
        <!-- 填充左侧内容 -->
        <div class="content-placeholder">
          <div ref="chartContainer" class="chart-container"></div>
        </div>
      </section>

      <!-- 右侧区块 (40%) -->
      <aside class="right-section">
        <!-- 填充右侧内容 -->
        <div class="content-placeholder">
          <div class="message-list">
            <h3 class="message-title">当前已接收消息：</h3>
            <ul class="message-items">
              <li 
                v-for="(item, index) in messageData" 
                :key="index"
                :class="{ 'highlight': item.dataValue >= 0.9 }"
              >
              {{ item.dataValue }} - {{ item.createdAt }}
              </li>
            </ul>
          </div>
        </div>
      </aside>
    </main>
  </div>
</template>

<script setup>
// 这里可以添加逻辑代码
import { useRouter } from 'vue-router'
import { ref, onMounted, onBeforeUnmount } from 'vue'
import api from '@/utils/request'
import * as echarts from 'echarts'

const router = useRouter()
const chartContainer = ref(null)
const messageData = ref([])
let chartInstance = null
let fetchInterval = null 

const taskEnabled = ref(false)  //状态

// 获取当前任务状态
const fetchTaskStatus = async () => {
  try {
    const response = await api.get('/api/task/status')
    taskEnabled.value = response.data
  } catch (error) {
    console.error('获取任务状态失败:', error)
  }
}

// 切换任务状态
const toggleTask = async (enabled) => {
  try {
    await api.post('/api/task/toggle', null, {
      params: { enable: enabled }
    })
    console.log(`定时任务已${enabled ? '开启' : '关闭'}`)
  } catch (error) {
    console.error('切换任务状态失败:', error)
    taskEnabled.value = !enabled  // 恢复原状态
  }
}

// 退出登录
const handleLogout = () => {
  localStorage.removeItem('isLogin')
  router.push('/login')
}


// 生成24小时数据静态方法
// const generateHourlyData = () => {
//   const timeData = []
//   const valueData = []
//   const now = new Date()
  
//   for (let hour = 0; hour < 24; hour++) {
//     const date = new Date(now.getFullYear(), now.getMonth(), now.getDate(), hour)
//     const timeString = date.toLocaleTimeString('zh-CN', { 
//       hour12: false, 
//       hour: '2-digit', 
//       minute: '2-digit'
//     }).slice(0, 5)
//     const value = Number(Math.random().toFixed(4))
//     timeData.push(timeString)
//     valueData.push(value)

//     存储消息数据
//     messageData.value.push({ time: timeString, value })
//   }
  
//   return { timeData, valueData }
// }

// 初始化图表
const initChart = () => {
  if (!chartContainer.value) return;
  
  chartInstance = echarts.init(chartContainer.value);
  
  // 基础配置（仅需设置一次）
  const baseOption = {
    tooltip: { trigger: 'axis' },
    xAxis: { type: 'category' },
    yAxis: { type: 'value', min: 0, max: 1 },
    series: [{ type: 'line', smooth: true }]
  };
  
  chartInstance.setOption(baseOption);
};

// 新增更新图表函数
const updateChart = () => {
  if (!chartInstance || !messageData.value.length) return;

  // 处理时间格式（假设 createdAt 格式为 "2025-04-28 23:31:16"）
  const timeData = messageData.value.map(item => {
    const [_, timePart] = item.createdAt.split(' ');
    return timePart.substring(0, 5);
  }).reverse();

  const valueData = messageData.value.map(item => item.dataValue);

  // 动态更新图表配置
  chartInstance.setOption({
    xAxis: { data: timeData },
    series: [{ data: valueData }]
  });
};

const fetchMessageData = async () => {
  try {
    
    // 调用后端接口验证
    const response = await fetch('http://localhost:8082/api/data') 

    const data = await response.json()
    messageData.value = data // 更新响应式数据
    updateChart()

    if (!response.ok) {
      throw new Error(await response.text())
    }

  } catch (err) {
    console.error('获取数据失败:', err)
  }
};

// 窗口resize处理
const handleResize = () => chartInstance?.resize()

// 初始化轮询
const startPolling = () => {
  fetchMessageData() // 立即执行第一次
  fetchInterval = setInterval(fetchMessageData, 5000) // 每5秒轮询
}

// 生命周期钩子
onMounted(() => {
  fetchTaskStatus()
  startPolling()
  initChart()
  window.addEventListener('resize', handleResize)
})

onBeforeUnmount(() => {
  clearInterval(fetchInterval) // 清除定时器
  window.removeEventListener('resize', handleResize)
  chartInstance?.dispose()
})
</script>



<style scoped>
/* 基础布局样式 */
.home-container {
  min-height: 80vh;
  min-width: 120vh;
  display: flex;
  flex-direction: column;
  background-color: #f5f7fa;
}

/* 顶部标题栏样式 */
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 30px;
  background-color: white;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.title {
  margin: 0;
  font-size: 24px;
  color: #2c3e50;
}

.auth-status {
  display: flex;
  align-items: center;
  gap: 15px;
}

.username {
  font-weight: 600;
  color: #3498db;
}

.logout-btn {
  padding: 6px 12px;
  background-color: #f1f5f9;
  border: 1px solid #e2e8f0;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.logout-btn:hover {
  background-color: #e2e8f0;
}

/* 主内容区样式 */
.main-content {
  flex: 1;
  display: flex;
  padding: 20px;
  gap: 20px;
}

.left-section {
  flex: 6; /* 60% */
  background-color: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.right-section {
  flex: 4; /* 40% */
  background-color: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

/* 内容占位样式 */
.content-placeholder {
  height: 90%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: #64748b;
  border: 1px dashed #e2e8f0;
  border-radius: 4px;
  padding: 20px;
}

.content-placeholder h3 {
  margin-top: 0;
  color: #334155;
}

/* 新增图表容器样式 */
.chart-container {
  width: 100%;
  height: 100%;
  min-height: 400px;
  padding: 10px;
}

/* 右侧消息列表样式 */
.message-list {
  max-height: 50vh;
  min-width: 40vh;
  height: 100%;
  padding: 10px;
}

.message-title {
  color: #2c3e50;
  margin: 0 0 15px 0;
  font-size: 16px;
  padding-bottom: 8px;
  border-bottom: 1px solid #e4e7ed;
}

.message-items {
  list-style: none;
  padding: 0;
  margin: 0;
  height: calc(100% - 40px);
  overflow-y: auto;
}

.message-items li {
  padding: 8px 12px;
  margin: 4px 0;
  border-radius: 4px;
  background-color: #f8f9fa;
  transition: background-color 0.3s;
  font-family: monospace;
}

.message-items li.highlight {
  color: #f56c6c;
  font-weight: 600;
}

.task-control {
  display: flex;
  align-items: center;
  gap: 15px;
  padding: 10px;
  background: #f5f7fa;
  border-radius: 4px;
  margin-bottom: 20px;
}

.status-text {
  font-size: 14px;
  color: #666;
}

/* 响应式适配 */
@media (max-width: 768px) {
  .main-content {
    flex-direction: column;
  }
  
  .left-section,
  .right-section {
    flex: none;
    width: 100%;
  }
}
</style>